package com.azh.server.tables;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.lifecycle.internal.LifecycleStarter;

import com.azh.server.parser.statement.Create;
import com.azh.server.parser.statement.Delete;
import com.azh.server.parser.statement.Insert;
import com.azh.server.parser.statement.Select;
import com.azh.server.parser.statement.SingleExpression;
import com.azh.server.parser.statement.Update;
import com.azh.server.parser.statement.Where;
import com.azh.server.tables.Field.ParseValueRes;
import com.azh.server.tx.TxManagerImpl;
import com.azh.server.util.ExceptionUtils;
import com.azh.server.util.Parser;
import com.azh.server.util.ParserStr;
import com.google.common.primitives.Bytes;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-05-01
 * Table 维护了表结构
 * 结构如下（二进制）
 * 一个数据库中存在多张表，我们用链表的方式存储，每个表都保存指向下一张表的uid
 * [TableName][NextTable]
 * [FieldUid][Field2Uid]...[FieldUid]
 */
public class Table {

    public TableManager tableM;

    public long uid;

    public String name;

    public byte status;

    public long nextUid;

    public List<Field> fieldList = new ArrayList<>();

    public Table(TableManager tableM, long uid) {
        this.tableM = tableM;
        this.uid = uid;
    }

    public Table(TableManager tableM, String tableName, long nextUid) {
        this.tableM = tableM;
        this.name = tableName;
        this.nextUid = nextUid;
    }

    public static Table loadTable(TableManager tableM, long uid) {
        byte[] raw = null;
        try {
            raw = ((TableManagerImpl) tableM).vm.read(TxManagerImpl.SUPER_TX_ID, uid);
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
        }
        assert raw != null;
        Table tb = new Table(tableM, uid);
        return tb.parseSelf(raw);
    }

    public static Table createTable(TableManager tbm, long nextUid, long xid, Create create) throws Exception {
        Table tb = new Table(tbm, create.tableName, nextUid);
        for(int i = 0; i < create.fieldName.length; i ++) {
            String fieldName = create.fieldName[i];
            String fieldType = create.fieldType[i];
            boolean indexed = false;
            for (int j = 0; j < create.index.length; j++) {
                if (fieldName.equals(create.index[j])) {
                    indexed = true;
                    break;
                }
            }
            tb.fieldList.add(Field.createField(tb, xid, fieldName, fieldType, indexed));
        }

        return tb.persistSelf(xid);
    }

    private Table parseSelf(byte[] raw) {
        int position = 0;
        ParserStr res = Parser.parserStr(raw);
        name = res.msg;
        position += res.next;
        nextUid = Parser.parseLong(Arrays.copyOfRange(raw, position, position + 8));
        position += 8;

        while(position < raw.length) {
            long uid = Parser.parseLong(Arrays.copyOfRange(raw, position, position + 8));
            position += 8;
            fieldList.add(Field.loadField(this, uid));
        }
        return this;
    }

    private Table persistSelf(long xid) throws Exception {
        byte[] nameRaw = Parser.stringToByte(name);
        byte[] nextRaw = Parser.longToByte(nextUid);
        byte[] fieldRaw = new byte[0];
        for(Field field : fieldList) {
            fieldRaw = Bytes.concat(fieldRaw, Parser.longToByte(field.uid));
        }
        uid = ((TableManagerImpl) tableM).vm.insert(xid, Bytes.concat(nameRaw, nextRaw, fieldRaw));
        return this;
    }

    private Map<String, Object> parseEntry(byte[] raw) {
        int pos = 0;
        Map<String, Object> entry = new HashMap<>();
        for (Field field : fieldList) {
            ParseValueRes r = field.parserValue(Arrays.copyOfRange(raw, pos, raw.length));
            entry.put(field.fieldName, r.v);
            pos += r.shift;
        }
        return entry;
    }

    public void insert(long xid, Insert insert) throws Exception {
        Map<String, Object> entry = stringToEntry(insert.values);
        byte[] raw = entryToRaw(entry);
        long uid = ((TableManagerImpl) tableM).vm.insert(xid, raw);
        for (Field field : fieldList) {
            if(field.isIndexed()) {
                field.insert(entry.get(field.fieldName), uid);
            }
        }
    }


    public int update(long txId, Update update) throws Exception {
        List<Long> uids = parseWhere(update.where);
        Field fd = null;
        for (Field f : fieldList) {
            if(f.fieldName.equals(update.fieldName)) {
                fd = f;
                break;
            }
        }
        if(fd == null) {
            throw new RuntimeException("Field not found!");
        }
        Object value = fd.stringToValue(update.value);
        int count = 0;
        for (Long uid : uids) {
            byte[] raw = ((TableManagerImpl) tableM).vm.read(txId, uid);
            if(raw == null) continue;

            ((TableManagerImpl) tableM).vm.delete(txId, uid);

            Map<String, Object> entry = parseEntry(raw);
            entry.put(fd.fieldName, value);
            raw = entryToRaw(entry);
            long uuid = ((TableManagerImpl) tableM).vm.insert(txId, raw);

            count ++;

            for (Field field : fieldList) {
                if (field.isIndexed()) {
                    field.insert(entry.get(field.fieldName), uuid);
                }
            }
        }
        return count;
    }

    public int delete(long txId, Delete delete) throws Exception {
        List<Long> uids = parseWhere(delete.where);
        int count = 0;
        for (Long uid : uids) {
            if (((TableManagerImpl) tableM).vm.delete(txId, uid)) {
                count++;
            }
        }
        return count;
    }

    private String printEntry(Map<String, Object> entry) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < fieldList.size(); i++) {
            Field field = fieldList.get(i);
            sb.append(field.printValue(entry.get(field.fieldName)));
            if (i == fieldList.size() - 1) {
                sb.append("]");
            } else {
                sb.append(", ");
            }
        }
        return sb.toString();
    }



    public String read(long txId, Select read) throws Exception {
        List<Long> uids = parseWhere(read.where);
        StringBuilder sb = new StringBuilder();
        for (Long uid : uids) {
            byte[] raw = ((TableManagerImpl) tableM).vm.read(txId, uid);
            if(raw == null) continue;
            Map<String, Object> entry = parseEntry(raw);
            sb.append(printEntry(entry)).append("\n");
        }
        return sb.toString();
    }

    private List<Long> parseWhere(Where where) throws Exception {
        long l0 = 0, r0 = 0, l1 = 0, r1 = 0;
        boolean single = false;
        Field field = null;
        if (where == null) {
            for (Field fd : fieldList) {
                if (fd.isIndexed()) {
                    field = fd;
                    break;
                }
            }
            l0 = 0;
            r0 = Long.MAX_VALUE;
            single = true;
        }else {
            for (Field fd : fieldList) {
                if (fd.fieldName.equals(where.singleExpression1.field)) {
                    if(!fd.isIndexed()) {
                        throw new RuntimeException("Field not indexed!");
                    }
                    field = fd;
                    break;
                }
            }
            if (field == null) {
                throw new RuntimeException("Field not indexed!");
            }
            CalWhereRes res = calWhere(field, where);
            l0 = res.l0; r0 = res.r0;
            l1 = res.l1; r1 = res.r1;
            single = res.single;
        }
        List<Long> uids = field.search(l0, r0);
        if(!single) {
            List<Long> tmp = field.search(l1, r1);
            uids.addAll(tmp);
        }
        return uids;
    }


    private CalWhereRes calWhere(Field fd, Where where) throws Exception {
        CalWhereRes res = new CalWhereRes();
        switch(where.logicOP) {
            case "":
                res.single = true;
                FieldCalRes r = fd.calExp(where.singleExpression1);
                res.l0 = r.left; res.r0 = r.right;
                break;
            case "or":
                res.single = false;
                r = fd.calExp(where.singleExpression1);
                res.l0 = r.left; res.r0 = r.right;
                r = fd.calExp(where.singleExpression2);
                res.l1 = r.left; res.r1 = r.right;
                break;
            case "and":
                res.single = true;
                r = fd.calExp(where.singleExpression1);
                res.l0 = r.left; res.r0 = r.right;
                r = fd.calExp(where.singleExpression2);
                res.l1 = r.left; res.r1 = r.right;
                if(res.l1 > res.l0) res.l0 = res.l1;
                if(res.r1 < res.r0) res.r0 = res.r1;
                break;
            default:
                throw new RuntimeException("Invalid logic operation!");
        }
        return res;
    }

    class CalWhereRes {
        long l0, r0, l1, r1;
        boolean single;
    }

    private Map<String, Object> stringToEntry(String[] values) throws Exception {
        if(values.length != fieldList.size()) {
            throw new RuntimeException("Invalid values!");
        }
        Map<String, Object> entry = new HashMap<>();
        for (int i = 0; i < fieldList.size(); i++) {
            Field f = fieldList.get(i);
            Object v = f.stringToValue(values[i]);
            entry.put(f.fieldName, v);
        }
        return entry;
    }

    private byte[] entryToRaw(Map<String, Object> entry) {
        byte[] raw = new byte[0];
        for (Field field : fieldList) {
            raw = Bytes.concat(raw, field.valueToRaw(entry.get(field.fieldName)));
        }
        return raw;
    }
}
